//
//  MYGMeetScheduleViewController.swift
//  MYDoctor
//
//  Created by Denny on 2024/5/28.
//

import UIKit

class MYGMeetScheduleViewController: MYGBaseController {
    
    var dateModels = [MYGMeetDateModel]()
    var detailModel = MYGMeetDetailModel()
    
    var contents:[[MYGScheduleCellModel]] = []
    
    var meeting_id:String = ""
    private lazy var searchTextField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(14)
        tf.textColor = .rgba(142, 142, 147, 1)
        tf.backgroundColor = .rgba(243, 243, 243, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 15
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.image(UIImage(named: "Chat/search"))
            confer.text(" 请输入标题或讲者搜索")?.font(.regular(14)).textColor(.rgba(142, 142, 147, 1))
        })
        tf.textAlignment = .center
//        tf.addTarget(self, action: #selector(textValueChanged), for: .editingChanged)
        return tf
    }()
    
    private lazy var searchBtn: UIView = {
        let btn = UIView()
        let tap = UITapGestureRecognizer(target: self, action: #selector(searchAction))
        btn.addGestureRecognizer(tap)
        return btn
    }()
    
    @objc func searchAction(){
        let vc = MYGScheduleOverviewViewController()
        vc.meeting_id = meeting_id
        self.navigationController?.pushViewController(vc)
    }
    
    var subTileView:MYGAcademicDetailSubtitleView = {
        let control = Bundle.main.loadNibNamed("MYGAcademicDetailSubtitleView", owner: nil)?.first as! MYGAcademicDetailSubtitleView
        control.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: 80)
        control.reserveBtn.isHidden = true
        return control
    }()
    
    lazy var dateCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 11
        var leftMargin = 18.0
        layout.itemSize = CGSize(width: 39, height: 44)
        let control = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        control.register(UINib.init(nibName: "MYGAcademicDetailDateCell", bundle: nil), forCellWithReuseIdentifier: "MYGAcademicDetailDateCell")
        
        control.showsHorizontalScrollIndicator = false
        control.showsVerticalScrollIndicator = false
        control.backgroundColor = .white
        control.delegate = self
        control.dataSource = self
        control.contentInset = UIEdgeInsets(top: 0, left: leftMargin, bottom: 0, right: leftMargin)
        return control
    }()

    lazy var tableView: UITableView = {
        let control = UITableView.init(frame: .zero, style: .plain)
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
//        control.rowHeight = 160
//        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
//        control.ww_foldable = true
        control.register(UINib.init(nibName: "MYGMeetScheduleTableViewCell", bundle: nil), forCellReuseIdentifier: "MYGMeetScheduleTableViewCell")
        return control
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "日程一览"
        addSubViews()
        getMeetDate()
        
    }
    
    func addSubViews() {
        view.backgroundColor = .white
        view.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(15)
            make.left.equalToSuperview().offset(17)
            make.right.equalToSuperview().offset(-17)
            make.height.equalTo(35)
        }
        view.addSubview(searchBtn)
        searchBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(15)
            make.left.equalToSuperview().offset(17)
            make.right.equalToSuperview().offset(-17)
            make.height.equalTo(35)
        }
        
        view.addSubview(subTileView)
        subTileView.snp.makeConstraints { make in
            make.top.equalTo(searchTextField.snp.bottom).offset(15)
            make.left.right.equalToSuperview()
            make.height.equalTo(80)
        }
        
        view.addSubview(dateCollectionView)
        dateCollectionView.snp.makeConstraints { make in
            make.top.equalTo(subTileView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(dateCollectionView.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
    
    func getMeetDate() {
        let par = ["meeting_id":meeting_id]
        MYGLoading.show()
        DennyNetwork.request(MYGHomePageAPI.meetingDetailTime(param: par), modelType: [MYGMeetDateModel].self) { obj in
            MYGLoading.hide()
            self.dateModels = obj
            self.dateCollectionView.reloadData()
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
                self.dateCollectionView.delegate?.collectionView?(self.dateCollectionView, didSelectItemAt: IndexPath(row: 0, section: 0))
            })
            self.getMeetDetail(model: self.dateModels.first!)
        } failed: { code, message in
            MYGLoading.hide()
            MMYGHUD.showToast(text: message)
        }
    }
    
    //会议详情
    func getMeetDetail(model:MYGMeetDateModel) {
        self.subTileView.model = model
        MYGLoading.show()
        MYGNetwork<MYGHomePageAPI, MYGMeetDetailModel>.request(target: .meetingDetail(param: ["meeting_id":meeting_id,"date":model.date])) {[weak self] result in
            MYGLoading.hide()
            guard let `self` = self else {return}
            self.detailModel = result
            self.bindData()

        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func bindData() {
        self.contents.removeAll()
        
//        var titles = [String]()
//        for(_,obj) in self.detailModel.data.enumerated() {
//            titles.append(obj.roomCn)
//        }
        //
        self.detailModel.data.forEach { model in
            
            var sections:[MYGScheduleCellModel] = []
            let cellModel = MYGScheduleCellModel(id: 0, time: "", titel: model.roomCn)
            sections.append(cellModel)
            
            model.session_info.forEach { item in
                let cellModel = MYGScheduleCellModel(id: item.id, time: item.sessionTime, titel: item.sessionCn)
                sections.append(cellModel)
            }
            self.contents.append(sections)
        }
        self.tableView.reloadData()
    }

}

extension MYGMeetScheduleViewController: UITableViewDelegate,UITableViewDataSource {
 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.contents.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let sections = self.contents[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "MYGMeetScheduleTableViewCell", for: indexPath) as! MYGMeetScheduleTableViewCell
        cell.models = sections
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 130
    }
    
}
extension MYGMeetScheduleViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
//        self.tableView.mj_header?.beginRefreshing()
        return true
    }
}
extension MYGMeetScheduleViewController:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.dateModels[indexPath.row]
        self.dateModels = self.dateModels.map({ obj in
            var result = obj
            result.isSelected = false
            if model.date == obj.date {
                result.isSelected = true
            }
            return result
        })
        self.dateCollectionView.reloadData()
        getMeetDetail(model: model)
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dateModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MYGAcademicDetailDateCell", for: indexPath) as! MYGAcademicDetailDateCell
        let model = dateModels[indexPath.row]
        cell.model = model
        return cell
    }
    
}
